﻿using Fluent;
using Microsoft.Practices.Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SampleApplication2.Regions
{
  public class RibbonRegionAdapter : RegionAdapterBase<Ribbon>
  {
    /// <summary>
    /// Default constructor.
    /// </summary>
    /// <param name="behaviorFactory">Allows the registration of the default set of RegionBehaviors.</param>
    public RibbonRegionAdapter(IRegionBehaviorFactory behaviorFactory)
      : base(behaviorFactory)
    {
    }

    /// <summary>
    /// Adapts a WPF control to serve as a Prism IRegion. 
    /// </summary>
    /// <param name="region">The new region being used.</param>
    /// <param name="regionTarget">The WPF control to adapt.</param>
    protected override void Adapt(IRegion region, Ribbon regionTarget)
    {
      region.Views.CollectionChanged += (sender, e) =>
      {
        switch (e.Action)
        {
          case NotifyCollectionChangedAction.Add:
            foreach (RibbonTabItem rti in e.NewItems)
            {
              regionTarget.Tabs.Add(rti);
            }
            break;

          case NotifyCollectionChangedAction.Remove:
            foreach (RibbonTabItem rti in e.OldItems)
            {
              if (regionTarget.Tabs.Contains(rti))
              {
                regionTarget.Tabs.Remove(rti);
              }
            }
            break;
        }
      };

      region.ActiveViews.CollectionChanged += (sender, e) =>
      {
        switch (e.Action)
        {
          case NotifyCollectionChangedAction.Add:
            foreach (FrameworkElement element in e.NewItems)
            {
              regionTarget.SelectedTabItem = (RibbonTabItem)element;
            }
            break;
        }
      };
    }

    protected override IRegion CreateRegion()
    {
      return new SingleActiveRegion();
    }
  }
}
